package com.cfuture08.eweb4j.helper;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.cfuture08.eweb4j.orm.config.bean.ORMConfigBean;
import com.cfuture08.eweb4j.orm.config.bean.Property;
import com.cfuture08.util.BeanXMLUtil;
import com.cfuture08.util.FileUtil;
import com.cfuture08.util.ReflectUtil;
import com.cfuture08.util.StringUtil;

/**
 * 将ORM配置信息写入xml文件
 * 
 * @author cfuture.aw
 * @since v1.a.0
 */
public class ORMConfigBeanWriter {
	public static String write(String filePath, Class<?>... clazzs) {
		String error = null;
		File file = new File(StringUtil.uriDecoding(FileUtil.getRootDir(ORMConfigBeanWriter.class)
				+ filePath));

		if (clazzs != null && clazzs.length > 0) {
			List<ORMConfigBean> ormList = new ArrayList<ORMConfigBean>();
			try {
				for (int i = 0; i < clazzs.length; ++i) {
					ORMConfigBean ormBean = new ORMConfigBean();
					ormBean.setClazz(clazzs[i].getName());
					ormBean.setId(clazzs[i].getSimpleName());
					ormBean.setTable("t_" + clazzs[i].getSimpleName());
					ReflectUtil ru;

					ru = new ReflectUtil(clazzs[i]);
					List<Property> pList = new ArrayList<Property>();
					for (Field f : ru.getFields()) {
						String name = f.getName();
						Property p = new Property();
						p.setName(name);
						p.setColumn(name);
						p.setType(f.getType().getName());
						pList.add(p);
					}
					ormBean.setProperty(pList);
					ormList.add(ormBean);
				}

				BeanXMLUtil.getBeanXMLWriter(file, ormList).write();
			} catch (Exception e) {
				error = e.getStackTrace().toString();
				e.printStackTrace();
			}

		} else {
			error = "Class参数不能为空";
		}

		return error;
	}
}
